#include "parafluidmpi.h"
#include "parafluidatom.h"
#include "parafluidsubstance.h"
#include "parafluidcolor.h"
#include "parafluidvector.h"
#include <QDebug>
#include <QByteArray>
#include <QDataStream>

using namespace ParaFluid;

Mpi::~Mpi(){}
Mpi::Mpi(){}

void Mpi::getAtom(char * & buffer, int & bufferSize)
{
	QByteArray data;
	QDataStream stream(&data, QIODevice::ReadWrite);

	// copy the number of atom in the stream
	int numAtom = 2;
	stream << numAtom;
		
	Vector position0(1.0, 1.1, 1.2);
	Substance substance0(0.5, Color::RED, 1.5, 2.0, 3.2);
	Atom atom0(position0, substance0);

	Vector position1(2.0, 3.1, 4.2);
	Substance substance1(0.8, Color::RED, 2.5, 5.0, 4.2);
	Atom atom1(position1, substance1);

	// copy the atoms to the stream
	stream << atom0;
	stream << atom1;
	
	bufferSize = data.size();
	//qDebug() << "!!bufferSize " << bufferSize;

	buffer = (char *) malloc(bufferSize);
	
	char * data1 = data.data();
	for(int i = 0; i < bufferSize; i++)
	{
		buffer[i] = *data1;
		++data1;
	}
}

void Mpi::showAtom(char * buffer, int bufferSize)
{
	QByteArray data(buffer, bufferSize);

	QDataStream stream(&data, QIODevice::ReadWrite);

	int numAtom;
	stream >> numAtom;
	
	qDebug() << "NumAtom = " << numAtom;
	
	for(int i = 0; i < numAtom; i++)
	{
		qDebug() << "  Atom : ";
				
		Atom atom;
		stream >> atom;
		
		qDebug() << "    Substance [Mass, Color, PressureFactor, RestDensity, ViscosityFactor] = [" 
		<< atom.substance.mass << ", " 
		<< "(" << atom.substance.color.red << ", " << atom.substance.color.green << ", " << atom.substance.color.blue << "), " 
		<< atom.substance.pressureFactor << ", " 
		<< atom.substance.restDensity << ", " 
		<< atom.substance.viscosityFactor << "]";
		
		qDebug() << "    currentDensity " << atom.currentDensity;
		qDebug() << "    currentForce    [x,y,z] = [" << atom.currentForce.x << ", " << atom.currentForce.y << ", " << atom.currentForce.z << "]";	
		qDebug() << "    currentPosition (x,y,z) = (" << atom.currentPosition.x << ", " << atom.currentPosition.y << ", " << atom.currentPosition.z << ")";	
		qDebug() << "    previousPosition(x,y,z) = (" << atom.previousPosition.x << ", " << atom.previousPosition.y << ", " << atom.previousPosition.z << ")";	
		qDebug() << "    nextPosition    (x,y,z) = (" << atom.nextPosition.x << ", " << atom.nextPosition.y << ", " << atom.nextPosition.z << ")";

	}
}
